<template>
  <select class="select select-bordered input-md w-full max-w-xs min-w-48" v-model="selectedValue" @change="valueChanged()">
    <option :value="undefined" v-if="undefinedOption">{{undefinedOption}}</option>
    <option v-if="extraOption" :value="extraOption.value">{{ extraOption.text }}</option>
    <option v-for="item in dataList" :value="getSelectText(item)">{{ getSelectText(item) }}</option>
  </select>
</template>

<script setup>
import {httpGet} from "~/utils/http/http-helper.js";
import {notificationSuccess} from "../utils/notification/index.js";

const props = defineProps({
  modelValue: Number,
  undefinedOption: String,
  uri: String,
  textKey: String,
  filter: Function,
  uniqueKey: String,
  extraOption: Object,
})
const dataList = ref([])
const selectedValue = ref(props.modelValue != null ? String(props.modelValue) : '')

watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal != null ? String(newVal) : ''
})

const emit = defineEmits(['update:modelValue'])

onMounted(() => {
  loadData()
})

function valueChanged(){
  emit('update:modelValue', selectedValue.value)
}

function loadData(){
  httpGet(props.uri).then(resp => {
    if(!resp.success){
      notificationSuccess(resp.msg)
      return
    }
    let filteredData = resp.data
    
    // Apply filter if provided
    if (props.filter) {
      filteredData = filteredData.filter(props.filter)
    }
    
    // Remove duplicates if uniqueKey is provided
    if (props.uniqueKey) {
      const seen = new Set()
      filteredData = filteredData.filter(item => {
        const value = item[props.uniqueKey]
        if (seen.has(value)) {
          return false
        }
        seen.add(value)
        return true
      })
    }
    
    dataList.value = filteredData
  })
}

function getSelectText(obj){
  return obj && props.textKey in obj ? obj[props.textKey] : ''
}

</script>

<style scoped>

</style>